<script setup>
import {emitter} from "@/utils/mitt";
import {useScriptTag} from '@vueuse/core'
import {CanvasRenderer} from "./canvasRenderer";
import {ref, onMounted, onBeforeUnmount} from "vue";

defineOptions({
  name: "VideoFrame"
});

const num = 200;
const curImg = ref("");
const renderer = ref();
const captureUtil = ref();
const loading = ref(false);
// const {loadScript} = useLoader();

const {VITE_PUBLIC_PATH} = import.meta.env;
const getPath = path => `${VITE_PUBLIC_PATH}wasm/${path}`;
const src = getPath("index.js");
const workerPath = getPath("capture.worker.js");
const wasmPath = getPath("capture.worker.wasm");

useScriptTag(src, () => {
  captureUtil.value = cheetahCapture.initCapture({
    workerPath,
    wasmPath
  });
});

onMounted(() => {
  renderer.value = new CanvasRenderer("canvas-container");
  emitter.on("imageInfo", info => (curImg.value = info.img.src));
});

function beforeUpload(file) {
  curImg.value = "";
  loading.value = true;
  renderer.value.clearImages();
  // api参考 https://github.com/wanwu/cheetah-capture#api
  captureUtil.value.then(res => {
    res.capture({
      // 视频文件
      file,
      // 抽取指定数目的帧图片，传递`number`是按照数目抽帧，传递数组是指定抽帧的时间，单位毫秒（抽帧策略：https://github.com/wanwu/cheetah-capture/issues/6#issuecomment-1634384486）
      info: 16,
      // 当抽帧结果变化的回调
      onChange: (list, {url}) => {
        // console.log(list, url)
        renderer.value.addImage(url, num * list.url.length, 0, num, num);
      },
      // 当抽帧结束并成功的回调
      onSuccess: () => {
        renderer.value.addListener();
        // 默认选中第一张
        renderer.value.drawTick({offsetX: num / 2, offsetY: num / 2});
        loading.value = false;
      },
      // 当抽帧过程出现错误的回调
      onError: () => {
        loading.value = false;
      }
    });
  });

  return false;
}

onBeforeUnmount(() => {
  // 解绑`imageInfo`公共事件，防止多次触发
  emitter.off("imageInfo");
});
</script>

<template>
  <el-card shadow="never">
    <template #header>
      <div class="card-header">
        视频帧截取
      </div>
    </template>
    <div class="flex flex-wrap">
      <el-upload
          drag
          :show-file-list="false"
          accept=".mp4,.mov,.avi,.webm,.mkv"
          :before-upload="beforeUpload"
      >
        <div class="el-upload__text">
          可拖拽上传视频（默认截取16张帧图片，可在代码中自行修改）
        </div>
      </el-upload>
      <el-image
          v-if="curImg"
          :src="curImg"
          :preview-src-list="Array.of(curImg)"
          class="w-[180px] h-[180px] ml-2 rounded-[6px]"
      />
    </div>
    <div
        id="canvas-container"
        v-loading="loading"
        element-loading-text="温馨提示：可左右拖拽图片并单击选取所需的帧图片"
        class="w-full h-[200px] overflow-hidden mt-6"
    />
  </el-card>
</template>

<style scoped lang="scss">
::v-deep(.el-upload-dragger) {
  display: flex;
  align-items: center;
  height: 180px;
}
</style>
